package org.jeecg.modules.hc.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.hc.constant.RedisConstant;
import org.jeecg.modules.hc.entity.HcMerchant;
import org.jeecg.modules.hc.entity.HcShoppingCart;
import org.jeecg.modules.hc.entity.HcSiteAddressDetails;
import org.jeecg.modules.hc.enums.HcIsFlagEnum;
import org.jeecg.modules.hc.service.IHcShoppingCartService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.hc.service.IHcSiteAddressDetailsService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 购物车
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
@Api(tags = "购物车")
@RestController
@RequestMapping("/hc/hcShoppingCart")
@Slf4j
public class HcShoppingCartController extends JeecgController<HcShoppingCart, IHcShoppingCartService> {
    @Autowired
    private IHcShoppingCartService hcShoppingCartService;

    @Autowired
    private IHcSiteAddressDetailsService hcSiteAddressDetailsService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 当用户点击【去结算】时，首先调用此方法，对用户购物车中的商品进行验证
     * @param addressId 用户所在大厦的id，对应于 hc_site_address_details表中的 id 列
     * @return
     */
    @ApiOperation("校验当前用户购物车列表")
    @GetMapping("/checkListByUser")
    public Result<?> checkListByUser(@RequestParam String addressId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        HcSiteAddressDetails hcSiteAddressDetails = hcSiteAddressDetailsService.getById(addressId);

        if (hcSiteAddressDetails == null) {
            return Result.error("大厦不存在，请重新选择大厦");
        }

        if (hcSiteAddressDetails.getState().equals(HcIsFlagEnum.NO)) {
            return Result.error("您选择的大厦今天休息哦，具体营业时间可以问群里的工作人员！");
        }

        List<HcMerchant> listByUser = hcShoppingCartService.getListByUser(sysUser.getId(), addressId);
        hcShoppingCartService.checkCommodityRequired(listByUser, addressId);
        return Result.ok();
    }

    @ApiOperation("清空购物车")
    @GetMapping("/doEmpty")
    public Result<?> doEmpty() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hcShoppingCartService.remove(new LambdaQueryWrapper<HcShoppingCart>()
                .eq(HcShoppingCart::getUserId, sysUser.getId())
        );
        redisUtil.del(RedisConstant.HC_SHOPPING + sysUser.getId());
        return Result.ok();
    }

    /**
     * 当点击【首页】左下角的 购物车图标时，调用此接口查询用户购物车中的商品
     * @param addressId 用户所在大厦id
     * @return
     */
    @ApiOperation("获取当前用户购物车列表")
    @GetMapping("/getListByUser")
    public Result<?> getListByUser(@RequestParam String addressId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(hcShoppingCartService.getListByUser(sysUser.getId(), addressId));
    }

    @ApiOperation("获取购物车统计")
    @GetMapping(value = "/getStatistics")
    public Result<?> getStatistics() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        HcShoppingCart hcShoppingCart = hcShoppingCartService.getOne(new QueryWrapper<HcShoppingCart>()
                .select("ifnull(sum(COMMODITY_QUANTITY), 0) as COMMODITY_QUANTITY", "ifnull(sum(COMMODITY_PRICE), 0) as COMMODITY_PRICE")
                .eq("USER_ID", sysUser.getId())
        );

        return Result.ok(hcShoppingCart);
    }

    /**
     * 分页列表查询
     *
     * @param hcShoppingCart
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "购物车-分页列表查询")
//	@ApiOperation(value="购物车-分页列表查询", notes="购物车-分页列表查询")
//	@GetMapping(value = "/list")
    public Result<IPage<HcShoppingCart>> queryPageList(HcShoppingCart hcShoppingCart,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<HcShoppingCart> queryWrapper = QueryGenerator.initQueryWrapper(hcShoppingCart, req.getParameterMap());
        Page<HcShoppingCart> page = new Page<HcShoppingCart>(pageNo, pageSize);
        IPage<HcShoppingCart> pageList = hcShoppingCartService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hcShoppingCart
     * @return
     */
//	@AutoLog(value = "购物车-添加")
    @ApiOperation(value = "购物车-添加", notes = "购物车-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_shopping_cart:add")
    @PostMapping(value = "/add")
    public Result<String> add(@Validated @RequestBody HcShoppingCart hcShoppingCart) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hcShoppingCart.setUserId(sysUser.getId());
        hcShoppingCartService.add(hcShoppingCart);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcShoppingCart
     * @return
     */
//	@AutoLog(value = "购物车-编辑")
//	@ApiOperation(value="购物车-编辑", notes="购物车-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_shopping_cart:edit")
//	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody HcShoppingCart hcShoppingCart) {
        hcShoppingCartService.updateById(hcShoppingCart);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//	@AutoLog(value = "购物车-通过id删除")
//	@ApiOperation(value="购物车-通过id删除", notes="购物车-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_shopping_cart:delete")
//	@DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcShoppingCartService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
//	@AutoLog(value = "购物车-批量删除")
//	@ApiOperation(value="购物车-批量删除", notes="购物车-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_shopping_cart:deleteBatch")
//	@DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcShoppingCartService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "购物车-通过id查询")
//	@ApiOperation(value="购物车-通过id查询", notes="购物车-通过id查询")
//	@GetMapping(value = "/queryById")
    public Result<HcShoppingCart> queryById(@RequestParam(name = "id", required = true) String id) {
        HcShoppingCart hcShoppingCart = hcShoppingCartService.getById(id);
        if (hcShoppingCart == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hcShoppingCart);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hcShoppingCart
     */
    //@RequiresPermissions("org.jeecg.modules:hc_shopping_cart:exportXls")
//    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcShoppingCart hcShoppingCart) {
        return super.exportXls(request, hcShoppingCart, HcShoppingCart.class, "购物车");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_shopping_cart:importExcel")
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcShoppingCart.class);
    }

}
